﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LIMS.Entities;
using LIMS.Shared;
namespace LIMS.Windows
{
    public partial class PlantManagement :LIMSPageBase<PlantManagementPresenter>, IPlantManagementPageView
    //public partial class PlantManagement   : Form
{
        public PlantManagement()
        {
            InitializeComponent();
        }

        /// <summary>
        /// bindDropDown
        /// </summary>
        private void bindDropDown()
        {
            try
            {
                bindStatus();
                bindSite();
            }
            catch (Exception ex)
            {
                Logger.Error("error while binding drop down ");
            }
        }

        private void bindSite()
        {
            try
            {
                Site oSite = new Site();
                List<Site> oSiteList = new List<Site>();
                oSite.Name = "--Select--";
                oSite.Id = 0;
                oSiteList = this.Presenter.GetAllSites();
                oSiteList.Insert(0, oSite);
                cmbSiteName.DataSource = oSiteList;
                cmbSiteName.ValueMember = "Id";
                cmbSiteName.DisplayMember = "Name";
            }
            catch (Exception ex)
            {
                Logger.Error("error while binding site");
            }
         
           
        }

        private void bindStatus()
        {

            cmbStatus.DataSource = Resource.BindStatus();
            cmbStatus.DisplayMember = "StatusValue";
            cmbStatus.ValueMember = "StatusKey";
        }


        /// if bValue is true contrlos will be enabled else disabled.
        /// </summary>
        /// <param name="bValue"></param>
        private void EnableDisableControls(bool bValue)
        {
            try
            {
                txtPlantLocation.Enabled = bValue;
                txtPlantName.Enabled = bValue;
                cmbStatus.Enabled = bValue;
                cmbSiteName.Enabled = bValue;
                btnSavePlant.Enabled = bValue;
                btnClear.Enabled = bValue;
            }
            catch (Exception ex)
            { 
            
            }
        }



        /// <summary>
        /// GetPlantBasedOnCriteria
        /// </summary>
        /// <param name="p_sCriteria"></param>
        private void GetPlantBasedOnCriteria(string p_sCriteria)
        {
            try
            {
                if (txtSearch.Text.Trim().Length == 0)
                {
                    this.Presenter.InitializeView();
                    DisplayGrid();
                }
                else
                {
                    this.Presenter.SearchPlantByKeyword(p_sCriteria);
                    DisplayGrid();
                }
                //DisplayGrid();
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }
        


        /// <summary>
        /// grdPlant_CellContentClick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdPlant_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            bool bChkBoxSelected = false;
            int iPlantID = Convert.ToInt32(grdPlant.Rows[grdPlant.CurrentRow.Index].Cells["Id"].Value);
            m_PlantId = iPlantID;

            for (int iRowCount = 0; iRowCount < grdPlant.Rows.Count; iRowCount++)
            {
                DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdPlant.Rows[iRowCount].Cells[0];
                if (cell is DataGridViewCheckBoxCell)
                {
                    if ((bool)cell.EditedFormattedValue)
                    {
                        bChkBoxSelected = true;
                        break;
                    }
                }
            }
            if (bChkBoxSelected)
            {
                btnDelete.Enabled = true;
                btnEdit.Enabled = true;
            }
            else
            {
                btnDelete.Enabled = false;
                btnEdit.Enabled = false;
                ClearData();
            }

        }
        private static int m_PlantId = 0;
        /// <summary>
        /// btnEdit_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (m_PlantId > 0)
            {
                int iSelectedRowsCount = 0;
                int iRowIndex = 0;
                for (int iRowCount = 0; iRowCount < grdPlant.Rows.Count; iRowCount++)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdPlant.Rows[iRowCount].Cells[0];
                    if (cell is DataGridViewCheckBoxCell)
                    {
                        if ((bool)cell.EditedFormattedValue)
                        {
                            iRowIndex = iRowCount;
                            iSelectedRowsCount++;
                        }
                    }
                }
                if (iSelectedRowsCount > 1)
                {
                    MessageBox.Show("Select single row to edit the record.");
                    return;
                }
                else if (iSelectedRowsCount == 0)
                {
                    MessageBox.Show("Select atleast one record to edit.");
                    return;
                }

                /// Edit
                CurrentIndex = iRowIndex;
                EnableDisableControls(true);
                btnClear.Enabled = false;
            }
        }
        /// <summary>
        /// btnDelete_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (m_PlantId > 0)
            {
                int iSelectedRowsCount = 0;
                for (int iRowCount = 0; iRowCount < grdPlant.Rows.Count; iRowCount++)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdPlant.Rows[iRowCount].Cells[0];
                    if (cell is DataGridViewCheckBoxCell)
                    {
                        if ((bool)cell.EditedFormattedValue)
                        {
                            iSelectedRowsCount++;
                        }
                    }
                }
                if (iSelectedRowsCount == 0)
                {
                    MessageBox.Show("Select atleast one record to delete.");
                    return;
                }

                DialogResult oResult = MessageBox.Show("Are you sure to delete the selected records?", "Delete site", MessageBoxButtons.YesNo);
                if (oResult.Equals(DialogResult.Yes))
                {
                    /// Delete
                    for (int iRowCount = 0; iRowCount < grdPlant.Rows.Count; iRowCount++)
                    {
                        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdPlant.Rows[iRowCount].Cells[0];
                        if (cell is DataGridViewCheckBoxCell)
                        {
                            if ((bool)cell.EditedFormattedValue)
                            {
                                if (CheckDepartmentDetailForPlant(oPlants[iRowCount].Id))
                                {
                                    this.Presenter.Delete(oPlants[iRowCount]);
                                }

                                else
                                {
                                    MessageBox.Show("This plant " + oPlants[iRowCount].Name + Resource.CANNOT_DELETE);
                                }
                            }
                        }
                    }
                    this.Presenter.InitializeView();
                    DisplayGrid();
                }

            }
        }

      
        /// <summary>
        /// CheckDepartmentDetailForPlant
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
     private bool CheckDepartmentDetailForPlant(int plantID)
      {
          bool bIsDeleted = false;
          bIsDeleted = this.Presenter.GetDepartmentByPlantId(plantID);
          return bIsDeleted;
      } 
        
        
        
        
        void DisplayGrid()
        {

            if (grdPlant.Columns[0].Displayed == false)
            {
                DataGridViewCheckBoxColumn oChkColumn = new DataGridViewCheckBoxColumn(false);

                oChkColumn.HeaderText = "Select";
                oChkColumn.Name = "Select";
                oChkColumn.Width = 50;

                grdPlant.Columns.Insert(0, oChkColumn);
            }

            grdPlant.MultiSelect = false;
            grdPlant.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grdPlant.AllowUserToAddRows = false;

            foreach (DataGridViewColumn dc in grdPlant.Columns)
            {
                if (dc.Index.Equals(0))
                {
                    dc.ReadOnly = false;
                }
                else
                {
                    dc.ReadOnly = true;
                }
            }
            grdPlant.RowHeadersVisible = false;
        }
        /// <summary>
        /// btnSaveSite_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSavePlant_Click(object sender, EventArgs e)
        {
            try
            {
                if (Validations.IsEmpty(txtPlantLocation.Text.Trim()) || Validations.IsEmpty(txtPlantName.Text.Trim()) ||
                    (Validations.IsCmbboxDefaultValue(Convert.ToString(cmbStatus.SelectedValue))) || Validations.IsCmbboxDefaultValue(Convert.ToString(cmbSiteName.SelectedValue)))
                {
                    MessageBox.Show("Fill mandatory(*) information.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    oPlants[CurrentIndex].Name = txtPlantName.Text;
                    oPlants[CurrentIndex].Location = txtPlantLocation.Text;
                    oPlants[CurrentIndex].SiteId = Convert.ToInt16(cmbSiteName.SelectedValue);
                    oPlants[CurrentIndex].Status = Convert.ToString(cmbStatus.SelectedValue);
                    oPlants[CurrentIndex].CreatedBy = 1; /// logged in user
                    oPlants[CurrentIndex].CreatedDateTime = DateTime.Now;


                    ///save site.
                    if (this.Presenter.Save(oPlants[CurrentIndex]))
                    {
                        MessageBox.Show("Plant saved successfully.");
                        EnableDisableControls(false);
                        btnEdit.Enabled = false;
                        btnDelete.Enabled = false;
                        ClearData();
                    }
                    ///intialize grid after saving site..
                    this.Presenter.InitializeView();
                    DisplayGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while saving site .");
            }
        }

        private void ClearData()
        {
            txtPlantName.Text = string.Empty;
            txtPlantLocation.Text = string.Empty;
            cmbStatus.SelectedValue = "X";
            cmbSiteName.SelectedValue = 0;
        }

        #region IPlantManagementPageView Members
        /// <summary>
        /// iCurrentIndex
        /// </summary>
        private int iCurrentIndex;
        public int CurrentIndex
        {
            set
            {
                iCurrentIndex = value;
                txtPlantName.Text = oPlants[iCurrentIndex].Name;
                txtPlantLocation.Text = oPlants[iCurrentIndex].Location;
                cmbSiteName.SelectedValue = oPlants[iCurrentIndex].SiteId;
                cmbStatus.SelectedValue = oPlants[CurrentIndex].Status;
                //cmbStatus.SelectedValue = Resource.GetCodedStatus(oSite[iCurrentIndex].Status, true);


            }
            get
            {
                return iCurrentIndex;
            }
        }
        /// <summary>
        /// FillPageData
        /// </summary>
        public void FillPageData()
        {
        }

        /// <summary>
        /// GridViewData
        /// </summary>
        private GridViewData oGridData;
        public GridViewData GridData
        {
            set
            {
                oGridData = value;
                lblTotal.Text = "/ " + (value.TotalRecords / value.PageSize + ((value.TotalRecords % value.PageSize > 0) ? 1 : 0)).ToString();
                txtPageNo.Text = value.PageIndex.ToString();
            }
            get
            {
                if (oGridData != null)
                {
                    return oGridData;
                }
                else
                {
                    GridViewData grdData = new GridViewData();
                    grdData.SortOrder = "ASC";
                    grdData.SortColumn = "CreatedDateTime";
                    grdData.PageSize = 10;//SetGridPageSize();
                    grdData.PageIndex = 1;
                    return grdData;
                }

            }
        }
        /// <summary>
        /// ShowMessage
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sMessage"></param>
        public void ShowMessage(MessageType type, string sMessage)
        {
            //throw new NotImplementedException();
        }

        private List<Plant> oPlants;
        public List<Plant> Plants
        {
            get
            {
                if (oPlants == null)
                {
                    oPlants = new List<Plant>();
                }
                return oPlants;
            }
            set
            {
                oPlants = value;
                grdPlant.DataSource = ConvertListToDataTable(oPlants);
                grdPlant.Columns[0].Visible = false;
            }
        }




        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddNewPlant_Click(object sender, EventArgs e)
        {
            EnableDisableControls(true);
            txtPlantName.Focus();
            Plant newplants = new Plant();
            oPlants.Add(newplants);
            CurrentIndex = oPlants.Count - 1;
            //bindStatus();
            cmbStatus.SelectedIndex = 0;
        }
        /// <summary>
        /// ConvertListToDataTable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private DataTable ConvertListToDataTable(List<Plant> list)
        {
            try
            {

                DataTable table = new DataTable();
                DataColumn oColumn0 = new DataColumn("Id", typeof(int));
                DataColumn oColumn1 = new DataColumn("Name", typeof(string));
                DataColumn oColumn2 = new DataColumn("Location", typeof(string));
                DataColumn oColumn3 = new DataColumn("SiteName", typeof(string));
                DataColumn oColumn4 = new DataColumn("Status", typeof(string));

                
                table.Columns.Add(oColumn0);
                table.Columns.Add(oColumn1);
                table.Columns.Add(oColumn2);
                table.Columns.Add(oColumn3);
                table.Columns.Add(oColumn4);


                for (int i = 0; i < list.Count; i++)
                {
                    DataRow oNewRow = table.NewRow();
                    oNewRow["Id"] = list[i].Id;
                    oNewRow["Name"] = list[i].Name;
                    oNewRow["Location"] = list[i].Location;
                    oNewRow["SiteName"] = list[i].SiteName;
                    oNewRow["Status"] = SharedResource.GetCodedStatus(list[i].Status);

                    table.Rows.Add(oNewRow);
                }
                return table;
            }

            catch (Exception ex)
            {
                Logger.Error("error while Convert List To DataTable in plant managment" + ex.ToString());
                return null;
            }
        }
        #endregion



        private void PlantManagement_Load(object sender, EventArgs e)
        {
            oGridData = null;
            bindDropDown();
         //   this.Presenter.InitializeView();
            GetPlantBasedOnCriteria(string.Empty);
            DisplayGrid();
            EnableDisableControls(false);
            btnDelete.Enabled = false;
            btnEdit.Enabled = false;
        }

        private void GridPagingToolTip()
        {
            System.Windows.Forms.ToolTip ToolTipText = new System.Windows.Forms.ToolTip();
            ToolTipText.SetToolTip(this.btnNext, "Next");
            ToolTipText.SetToolTip(this.btnFirst, "First");
            ToolTipText.SetToolTip(this.btnPrevious, "Previous");
            ToolTipText.SetToolTip(this.btnLast, "Last");
            ToolTipText.SetToolTip(this.btnSpecific, "Go to specific");
        }
        /// <summary>
        /// btnSearch_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string sCriteria = txtSearch.Text.Trim();
            if (sCriteria.Length > 0)
            {
                if (sCriteria.Contains("*"))
                {
                    if (sCriteria.Equals("*"))
                    {
                        sCriteria = string.Empty;
                    }
                    else
                    {
                        sCriteria = sCriteria.Replace("*", "%");
                    }
                }
                else if (sCriteria.Contains("?"))
                {
                    sCriteria = sCriteria.Replace("?", "%");
                }
            }
            GetPlantBasedOnCriteria(sCriteria);
            ClearData();
        }
        /// <summary>

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            try
            {
                if (GridData.PageIndex > 1)
                {
                    GridData.PageIndex--;
                    GetPlantBasedOnCriteria(string.Empty);
                  
                }
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }

        }


        private void btnLast_Click(object sender, EventArgs e)
        {
            try
            {
                GridData.PageIndex = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0));
                GetPlantBasedOnCriteria(string.Empty);
              
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnSpecific_Click(object sender, EventArgs e)
        {
            try
            {
                int userCurrentPage = 0;

                if (!int.TryParse(txtPageNo.Text, out userCurrentPage))
                {
                    userCurrentPage = 1;
                }

                int maxPageSize = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0));
                if (userCurrentPage > maxPageSize)
                {
                    userCurrentPage = 1;
                }
                GridData.PageIndex = userCurrentPage;
                GetPlantBasedOnCriteria(string.Empty);
             
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                int maxPageSize = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0) - 1);

                if (GridData.PageIndex <= maxPageSize)
                {
                    GridData.PageIndex++;
                    GetPlantBasedOnCriteria(string.Empty);
                    

                }
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

      

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearData();
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            try
            {
                GridData.PageIndex = 1;//(GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0) -1 );
                GetPlantBasedOnCriteria(string.Empty);
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

       

       

       
    }
}
